package show.me.the.money.util;

import java.io.IOException;
import java.net.UnknownHostException;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.context.WebApplicationContext;

import show.me.the.money.util.context.Context;

import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.MongoOptions;
import com.mongodb.ServerAddress;


public class MongoUtil {
	private static boolean isReady;
	private static Mongo m;
	
	public static void init() throws UnknownHostException, MongoException, IOException{
		if(m == null){
			WebApplicationContext wac = AppContextHolder.get();
			Context ctx = (Context)wac.getBean("staticInitContext");
			String cfgServerIp = ctx.value("server.configServerIp");
			String cfgServerport = ctx.value("server.configServerPort");
			if(!StringUtils.isEmpty(cfgServerIp) && !StringUtils.isEmpty(cfgServerport)){
				int port = Integer.valueOf(cfgServerport);
				m = create(cfgServerIp, port);
				m.getDatabaseNames();  // test mongoDB is alived
				isReady = true;
			}
		}
	}
	
	private static Mongo create(String host, int port) throws UnknownHostException, MongoException{
		MongoOptions mp = new MongoOptions();
		mp.autoConnectRetry = false;
		mp.connectionsPerHost = 100;		//default is 10
		mp.threadsAllowedToBlockForConnectionMultiplier = 50;
		mp.maxWaitTime = 10000;
		ServerAddress sa = new ServerAddress(host , port);;
		Mongo svr = new Mongo(sa , mp);
		return svr;
	}
	public static Mongo getMongo() {
		return m;
	}
	public static boolean isReady() {
		return isReady;
	}
	
	public static void main(String[] args) throws UnknownHostException, MongoException {
//		Mongo mo = create("172.16.170.41", 9002);
//		mo.getConnector().getMaxBsonObjectSize();
//		mo.getMaxBsonObjectSize();
//		DB db =  mo.getDB("test");
//		db.getStats();
//		DBCollection c = db.getCollection("onlineuser");
//		DBCursor b = c.find();
//		while(b.hasNext()){
//			DBObject o = b.next();
//			System.out.println(o.get("isOnline") instanceof Boolean);
//			System.out.println(o.get("logonTime") instanceof Date);
//			break;
//		}
	}
}
